/*
 * ================================================================================变量定义区
 */
var optype = ""; //定义操作类型为 create/update
var currentPage = 1;//全局变量，当前页
var passwordBefore ="";//密码未修改时
var passwordChanged = "";//提交时密码
var validateRules = "";//校验规则
/*
 * ================================================================================页面初始化函数
 */
$(function()
{
	
	//获取隐藏的用户名
	var username = $("#hiddenUsername").val().trim();
	
	//判断点击类型
	if(username && username.length>0)
	{
		optype = "update";
		$("#pageName").empty().append("update user");
		$("#username").attr("disabled","disabled");
		passwordBefore = $("#userForm input[name=password]").val();
	}
	else
	{
		optype = "create";
		$("#username").removeAttr("readonly");
		$("#pageName").empty().append("create user");
	}
	

	//加载验证规则
	setRules();
	
	//启动验证
	$("#userForm").validate(validateRules);
	
	//加载树
	departmentTree();
	
	//绑定事件
	$("#btnSubmit").bind('click',function()
	{
		submitData();
	});
	$("#btnCancel").bind('click',function()
	{
		cancel();
	});
	
	//角色选择 单击添加选中角色项
	$('#add').click(function() 
	{
		var $options = $('#select1 option:selected'); //获取选中的选项
		$options.appendTo('#select2'); //追加给对方（append方法可以实现删除追加两个步骤
	});
	
	//角色选择 单击添加所有角色项
	$('#add_all').click(function() 
	{
		var $options = $('#select1 option');
		$options.appendTo('#select2');
	});
	
	//角色选择 双击添加选中角色项
	$('#select1').dblclick(function() 
	{
		var $options = $("option:selected", this);
		$options.appendTo('#select2');
	});
	
	//角色选择 单击删除选中角色项
	$('#remove').click(function() 
	{
		var $options = $('#select2 option:selected'); //获取选中的选项
		$options.appendTo('#select1'); //追加给对方（append方法可以实现删除追加两个步骤
	});
	
	//角色选择 单击删除所有角色项
	$('#remove_all').click(function() 
	{
		var $options = $('#select2 option');
		$options.appendTo('#select1');
	});
	
	//角色选择 双击删除选中角色项
	$('#select2').dblclick(function() 
	{
		var $options = $("option:selected", this);
		$options.appendTo('#select1');
	});
	
});

/*
 * ================================================================================函数定义区
 * 
 */

/**
 * 设置验证规则
 */
function setRules()
{
	validateRules = 
	{
		rules: 
		{
			username:
			{
				required:true,
				userNameCheck:true,
				
				remote:
				{
					type:"post",
					url:BASE_PATH+"/userManagement/checkName.do",
					async: false,
					data:
					{
		                 username:function()
		                 {
		                	 return $("#username").val().trim()+","+optype;
		                 }
		             }  
		        },
		        nameMaxLength:true
			},
			
			password:
			{
				required:true,
				formatRule:true
			},
			
			user_status:
			{
				user_status:true,
				required:true
			},
			
			cn_name:
			{
				required:true,
				cnNameCheck:true
			},
			
			email:
			{
				required:true,
				email:true
			},
			
			emp_code:
			{
				required:true,
				codeMaxLength:true
			}
		},
		
		messages:
		{
			username:
			{
				required:"请输入USERNAME",
				userNameCheck:"请输入2-12位字母、数字或“.”",
				remote:jQuery.format("USERNAME已存在,请重新输入"),
				nameMaxLength:jQuery.format("USERNAME过长,请重新输入")
			},
			
			password:
			{
				required:"请输入PASSWORD",
				formatRule:"请输入4到15位数字、字母或“_”"
			},
			
			user_status:
			{
				user_status:"请选择USER_STATUS",
				required:"请选择USER_STATUS"
			},
			
			cn_name:
			{
				required:"请输入CN_NAME",
				cnNameCheck:"请输入2-30位汉字,字母,数字或“_”"
			},
			
			email:
			{
				required:"请输入EMAIL",
				email:"请输入合法EMAIL"
			},
			
			emp_code:
			{
				required:"请输入EMP_CODE",
				codeMaxLength:jQuery.format("EMP_CODE过长,请重新输入")
			}
		}
	};
	
	//验证user_status选中否
	$.validator.addMethod("user_status", function(value, element) 
	{   
	    var status = $("#user_status option:selected").val();
	    var result = true;
	    
	    if (status == "----请选择状态----")
	    {
	    	result = false;
	    }
	    
	    return result;
	}
	, "请选择USER_STATUS");
	
	//验证username长度是否符合要求
	$.validator.addMethod("nameMaxLength",function(value,element)
	{
		var name = $("#username").val().trim();
		var totalLength = checkStringLength(name);
		var result = true;
		
		//判断长度是否大于数据库长度
		if(totalLength-32>0)
		{
			result = false;
		}
		
		return result;
	}
	,"USERNAME过长,请重新输入");
	
	//验证emp_code长度是否符合要求
	$.validator.addMethod("codeMaxLength",function(value,element)
	{
		var name = $("#emp_code").val().trim();
		var totalLength = checkStringLength(name);
		var result = true;
		
		//判断长度是否大于数据库长度
		if(totalLength-32>0)
		{
			result = false;
		}
		
		return result;
	}
	,"EMP_CODE过长,请重新输入");
	
	//验证密码格式只能输入数字字母和下划线
	$.validator.addMethod("formatRule",function(value,element)
	{
		var password = $("#password").val();
		var match = /^[0-9_a-zA-Z*]{4,15}$/;
		return match.test(password);
	}
	,"请输入4到15位数字、字母或_");
	
	//验证输入的字符是否为英文字母、数字
	$.validator.addMethod("userNameCheck", function(value, element)
	{
		value = $("#username").val().trim();
		return this.optional(element) ||/^[a-zA-Z0-9.]{2,12}$/.test(value);
	}
	,"请输入2-12位字母、数字或“.”");
	

	//验证输入的字符是否为英文字母、汉字、数字和下划线
	$.validator.addMethod("cnNameCheck", function(value, element)
	{
		value = $("#cn_name").val().trim();
		return this.optional(element) ||/^[\u4e00-\u9fa5_a-zA-Z0-9]{2,30}$/.test(value);
	}
	,"请输入2-30位汉字,字母,数字或“_”");
}

/**
 * 获取输入字符串的unicode长度
 * @param name 输入的字符串
 * @returns totalLength 字符串的unicode长度
 */
function checkStringLength(name)
{
	var totalLength = 0;
	var charCode = 0; 
	
	for (var i = 0; i < name.length; i++) 
	{ 
		charCode = name.charCodeAt(i);
		
		if (charCode < 0x007f) 
		{ 
			totalLength = totalLength + 1; 
		} 
		else if ((0x0080 <= charCode) && (charCode <= 0x07ff)) 
		{ 
			totalLength += 2; 
		}
		else if ((0x0800 <= charCode) && (charCode <= 0xffff))
		{ 
			totalLength += 3; 
		} 
	} 
	return totalLength;
}

/**
 * submit 提交
 */
function submitData()
{
	
	//提交时再进行验证
	var validateResult = $("#userForm").validate(validateRules).form();
	
	//判断验证是否通过
	if(!validateResult)
	{
		openAlert("请按提示填写完整信息");
		return;
	}
	else
	{
		var passwordChanged = isPasswordChange();
		
		$.ajax(
		{
			type: 'POST',
	        url: BASE_PATH +'/userManagement/addOrUpdateUser.do',
	        dataType:"json",
			data:
			{
				"username" 		: 	$("#username").val().trim(),
				"password" 		: 	passwordChanged,
				"cn_name"  		: 	$("#cn_name").val().trim(),
				"email"    		:	$("#email").val().trim(),
				"emp_code" 		: 	$("#emp_code").val().trim(),
				"user_status" 	: 	$("#user_status").val(),
				"dept_id"		:  	$("#dept_id").val(),
				"role_name"		: 	getRoles(),
				"optype"		:	optype
				
			},
			
			success : function(data) 
			{
				
				if(data=='success')
				{
					openAlert('保存成功',function()
					{
						backToCurrentPage();
					});
				}
				else
				{
					openAlert(data);
				}
				
			},
			
			error:function(e)
			{
				openAlert('操作失败！错误信息：<div>'+e.responseText+"</div>");
			}
		});
	}
	
}
/**
 * 检查密码是否未改变
 * @returns passwordChanged 密码改变后加密的密码
 */
function isPasswordChange()
{
	var username = $("#username").val().trim();
	var password = $("#password").val();
	
	if(password == "***********")
	{
		passwordChanged = '';
	}
	else
	{
		
		$.ajax(
			{
				type: 'POST',
			    url: BASE_PATH +'/userManagement/checkPassword.do',
			    dataType:"json",
			    async: false,
				data:
				{
					"username":username,
					"password":$.md5(password)
				},
				
				success:function(data)
				{
					
					if(data==true)
					{
						passwordChanged='';
					}
					else
					{
						passwordChanged = $.md5(password);
					}
				},
				
				error:function(e)
				{
					openAlert('操作失败！错误信息：<div>'+e.responseText+'</div>');
				}
			});
	}
	return passwordChanged;
}

/**
 * cancel button
 * 取消按钮事件
 */
function cancel()
{
	
	openConfirm('确定取消吗？', null, function() 
	{
		backToCurrentPage();
	});
	
}

/**
 * 加载树和树的点击事件
 */
function departmentTree()
{
	
	var setting = 
	{
			view: 
			{
				dblClickExpand: false
			},
			
			data: 
			{
				
				key: 
				{
					title:"titleTip"
				},
				
				simpleData: 
				{
					enable: true
				}
			},
			
			callback:
			{
				beforeClick: beforeClick,
				onClick: onClick
			}
		};

	var zNodes = '[';
	
	$.ajax(
	{
		type: 'POST',
        url: BASE_PATH +'/userManagement/queryDepts.do',
        dataType:"json",
        data:
        {
        	
        },
        
        success:function(data,textStatus)
        {
        	
        	for( var i = 0; i < data.length; i++ )
        	{
        		zNodes += '{id:"' + convertSpecialChar(data[i].deptId) + '",';
        		zNodes += 'pId:"' + convertSpecialChar(data[i].parentId) + '",';
        		zNodes += 'name:"' + convertSpecialChar( data[i].deptName ) + '",';
        		zNodes += 'titleTip:"' + convertSpecialChar( data[i].deptName ) + '",';
        		
        		if( data[i].deptDesc == null )
        		{
            		zNodes += 'deptDesc:"",';
        		} 
        		else 
        		{
            		zNodes += 'deptDesc:"' + convertSpecialChar( data[i].deptDesc ) + '",';
        		}
        		zNodes += 'isLeaf:"' + data[i].isLeaf + '",';
        		zNodes += 'open:true}';
        		
        		if( i != (data.length - 1) )
        		{
        			zNodes += ',';
        		}
        	}
        	zNodes += ']';
    		// 加载树
    		$.fn.zTree.init($("#departmentTree"), setting, eval(zNodes));
    		//选中已有部门
    		var chooseId=$("#dept_id").val();
    		deptIsChoosed(chooseId);
        },
        
		error:function(e)
		{
			openAlert("加载数据错误！"); 
			return;
		}
	});
	
}

/**
 * 让已被选的部门在树中处于被选中状态
 * @param id 所选部门的id 
 */
function deptIsChoosed(id)
{
	var zTree = $.fn.zTree.getZTreeObj("departmentTree");
	var node = zTree.getNodeByParam("id",id,null);
	zTree.selectNode(node);
}

/**
 * 树点击前事件
 * @param treeId 树id
 * @param treeNode 树节点对象
 * @returns check 返回被选节点是否可选
 */
function beforeClick(treeId, treeNode) 
{
	var check = (treeNode && !treeNode.isParent);
	if (!check) openAlert("请选择具体部门！");
	return check;
	
}

/**
 * 树单击事件
 * @param e js的event对象
 * @param treeId 树id
 * @param treeNode 树节点对象
 */
function onClick(e, treeId, treeNode) 
{
	var zTree = $.fn.zTree.getZTreeObj("departmentTree"),
		nodes = zTree.getSelectedNodes(),
		v = "",
		id = "";
	nodes.sort(function compare(a,b){return a.id-b.id;});
	
	for (var i=0, l=nodes.length; i<l; i++) 
	{
		v += nodes[i].name + ",";
		id += nodes[i].id + ",";
	}
	
	if (v.length > 0 ) v = v.substring(0, v.length-1);
	
	if (id.length >0 ) id = id.substring(0,id.length-1);
	
	var cityObj = $("#dept_name");
	cityObj.attr("value", v);
	var deptId = $("#dept_id");
	deptId.attr("value",id);
	hideMenu();
	
}

/**
 * 显示树
 */
function showMenu() 
{
	
	var cityObj = $("#dept_name");
	var cityOffset = $("#dept_name").offset();
	$("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top 
		+ cityObj.outerHeight() + "px"}).slideDown("fast");
	$("body").bind("mousedown", onBodyDown);
	
}

/**
 * 隐藏树
 */
function hideMenu() 
{
	
	$("#menuContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDown);
	
}

/**
 * 判断是否隐藏树
 * @param event 事件源
 */
function onBodyDown(event)
{
	
	if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" 
		|| $(event.target).parents("#menuContent").length>0)) 
	{
		hideMenu();
	}
	
}

/**
 * 获取所有选中角色并拼接成字符串
 * @returns roles 返回角色字符串
 */
function getRoles()
{
	
	var $id = $("#select2 option");
	var roles = "";
	
	//若角色数不为0，拼接角色
	for(var i=0;i<$id.size();i++)
	{
		var $option = $id.eq(i);
		
		if(i==($id.size()-1))
		{
			roles += $option.text();
			break;
		}
		roles += $option.text()+",";
	}
	return roles;
	
}


/**
 * 返回当前页
 */
function backToCurrentPage()
{
	$("#submitcurrentpage").submit();
}
